<template>
  <div class="main-list">
    <div class="list-head">
      <div class="head-left">
        <img src="@/assets/static/order.png" alt="" class="head-icon">
        <div class="head-name">专栏订单</div>
      </div>
      <div class="head-right" @click="toOrder">查看更多数据
        <i class="el-icon-arrow-right" />
      </div>
    </div>
    <div class="head-timer">
      <div class="timer-name">时间：</div>
      <el-date-picker
        v-model="dateTime"
        type="datetimerange"
        prefix-icon=""
        range-separator="~"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :default-time="['00:00:00', '23:59:59']"
        @change="onClick"
      />
      <el-button type="primary" @click="settimer">查询</el-button>
      <div class="timer-reset">
        <el-button type="info" @click="resettimer">重置</el-button>
      </div>
    </div>
    <div class="list-nav">
      <el-table
        id="table"
        ref="multipleTable"
        v-loading="loading"
        element-loading-text="加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.3)"
        :data="tableData"
        :height="tableH"
        size="mini"
        stripe
        tooltip-effect="dark"
        style="width: 100%"
        @select="onSelect"
        @select-all="onSelectAll"
      >
        <el-table-column type="selection" width="30" />
        <el-table-column prop="no" align="center" label="专栏号" width="75" />
        <el-table-column label="专栏名" align="center" width="75">
          <template slot-scope="scope">
            <div
              class="table-name"
              :title="scope.row.name"
            >
              <span
                class="name-text"
                :class="{ 'auto-scroll': shouldScroll(scope.row.name) }"
              >
                {{ scope.row.name }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="scheme_order_sum" align="right" label="方案总收入" sortable width="100" />
        <el-table-column prop="column_card_order_sum" align="right" label="优惠卡总收入" sortable width="120" />
        <el-table-column prop="total_order_sum" align="right" label="专栏总收入" sortable width="100" />
        <el-table-column prop="column_vip_order_sum" align="right" label="VIP总收入" sortable width="105" />
        <el-table-column prop="scheme_order_refund_sum" align="right" label="方案总退款" sortable width="105" show-overflow-tooltip />

        <!-- 加载状态行 -->
        <el-table-column v-if="isLoading || !hasMoreData" width="100%">
          <template slot="header">
            <span />
          </template>
          <template>
            <div />
          </template>
        </el-table-column>
      </el-table>

      <!-- 表格底部加载状态 -->
      <div v-if="isLoading || !hasMoreData" class="table-footer">
        <div v-if="isLoading" class="loading-row">
          <i class="el-icon-loading" />
          <span>加载中...</span>
        </div>
        <div v-else-if="!hasMoreData" class="no-more-row">
          <span>没有更多数据了</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import _ from 'lodash'

export default {
  components: {

  },
  props: {
    tableH: {
      type: [String, Number],
      default: '0'
    },
    tableData: {
      type: Array,
      default: () => []
    },
    hasMoreData: {
      type: Boolean,
      default: true
    },
    isLoading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dateTime: '',
      setTime: '',
      scrollHandler: null,
      resizeObserver: null,
      loading: true,
      autoLoadCount: 0, // 自动加载计数器
      maxAutoLoad: 3, // 最大自动加载次数
      isCheckingHeight: false
    }
  },
  computed: {
    // 计算文本是否应该滚动（文本长度超过5个字符）
    shouldScroll() {
      return (name) => {
        return name && name.length > 5
      }
    }
  },
  watch: {
    tableData: {
      handler(newVal) {
        this.loading = false
        // 数据更新后检查高度
        this.onTableDataUpdate()
      },
      deep: true
    },
    // 监听搜索条件变化，重置自动加载
    dateTime() {
      this.resetAutoLoad()
    }
  },
  mounted() {
    this.initScrollListener()
    this.initHeightChecker()
  },
  beforeDestroy() {
    this.removeScrollListener()
    this.removeHeightChecker()
  },
  methods: {
    // 初始化高度检查
    initHeightChecker() {
      // 使用 ResizeObserver 监听表格容器高度变化
      this.resizeObserver = new ResizeObserver(_.debounce(() => {
        this.checkTableHeight()
      }, 300))

      this.$nextTick(() => {
        const tableWrapper = document.querySelector('.el-table__body-wrapper')
        if (tableWrapper) {
          this.resizeObserver.observe(tableWrapper)
        }

        // 初始检查
        setTimeout(() => {
          this.checkTableHeight()
        }, 500)
      })
    },

    // 移除高度检查
    removeHeightChecker() {
      if (this.resizeObserver) {
        this.resizeObserver.disconnect()
        this.resizeObserver = null
      }
    },

    // 检查表格高度，判断是否需要自动加载更多数据
    checkTableHeight() {
      if (this.isCheckingHeight || this.isLoading || !this.hasMoreData) {
        return
      }

      this.isCheckingHeight = true

      this.$nextTick(() => {
        const tableBody = document.querySelector('.el-table__body-wrapper')
        const tableBodyContent = document.querySelector('.el-table__body')

        if (!tableBody || !tableBodyContent) {
          this.isCheckingHeight = false
          return
        }

        // 获取可视区域高度和内容高度
        const visibleHeight = tableBody.clientHeight
        const contentHeight = tableBodyContent.clientHeight

        // 如果内容高度小于可视区域高度，说明数据不足以填满表格
        // 并且还有更多数据可加载，且自动加载次数未达到上限
        if (contentHeight < visibleHeight &&
            this.hasMoreData &&
            this.autoLoadCount < this.maxAutoLoad) {
          console.log('表格未填满，自动加载更多数据', {
            contentHeight,
            visibleHeight,
            autoLoadCount: this.autoLoadCount
          })

          this.autoLoadCount++
          this.loadMoreData()
        }

        this.isCheckingHeight = false
      })
    },

    // 在数据更新后检查高度
    onTableDataUpdate() {
      this.$nextTick(() => {
        setTimeout(() => {
          this.checkTableHeight()
        }, 300)
      })
    },

    initScrollListener() {
      const el = document.getElementsByClassName('el-table__body-wrapper')[0]
      if (!el) return

      this.removeScrollListener()

      this.scrollHandler = _.debounce(() => {
        const { scrollTop, clientHeight, scrollHeight } = el

        if (scrollTop + clientHeight >= scrollHeight - 10) {
          // 滚动到底部时重置自动加载计数器
          this.autoLoadCount = 0
          this.loadMoreData()
        }
      }, 200)

      el.addEventListener('scroll', this.scrollHandler)
    },

    removeScrollListener() {
      const el = document.getElementsByClassName('el-table__body-wrapper')[0]
      if (el && this.scrollHandler) {
        el.removeEventListener('scroll', this.scrollHandler)
      }
    },

    loadMoreData() {
      if (this.isLoading || !this.hasMoreData) {
        return
      }

      this.$emit('loadMore', 1)
    },

    // 重置自动加载计数器
    resetAutoLoad() {
      this.autoLoadCount = 0
    },

    onSelect(e) {
      const ids = e.map(ele => {
        return ele.id
      }).join(',')
      this.$emit('tableIds', ids)
    },

    onSelectAll(e) {
      const ids = e.map(ele => {
        return ele.id
      }).join(',')
      this.$emit('tableIds', ids)
    },

    resettimer() {
      this.dateTime = ''
      this.resetAutoLoad()
      this.$emit('dateChange', this.dateTime)
    },

    settimer() {
      this.resetAutoLoad()
      this.$emit('dateChange', this.setTime)
    },

    onClick(e) {
      const arr = e.map(date => {
        const year = date.getFullYear()
        const month = (date.getMonth() + 1).toString().padStart(2, '0')
        const day = date.getDate().toString().padStart(2, '0')
        const hours = date.getHours().toString().padStart(2, '0')
        const minutes = date.getMinutes().toString().padStart(2, '0')
        const seconds = date.getSeconds().toString().padStart(2, '0')
        const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
        return formattedDate
      })
      this.setTime = `${arr[0]} - ${arr[1]}`
      this.resetAutoLoad()
      this.$emit('dateChange', `${arr[0]} - ${arr[1]}`)
    },

    toOrder() {
      window.open('https://server.geiqiutiyu.com/caizhan.php/order/column?ref=addtabs')
    }
  }
}
</script>

<style scoped lang="scss">
.el-table {
  ::v-deep .el-table__body-wrapper::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }

  ::v-deep .el-table__body-wrapper::-webkit-scrollbar-track {
    background-color: #56517A;
  }

  ::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background-color: #2C2559;
  }
}

::v-deep .el-table--striped .el-table__body tr.el-table__row--striped td {
  background-color: #342F66;
}

.main-list {
  box-sizing: border-box;
  background: #2C2559;
  border-radius: 24px;
  padding: 20px;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .list-head {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .head-left {
      display: flex;
      align-items: center;
      font-size: 18px;
      font-weight: 400;
      color: rgba(255, 255, 255, 1);

      .head-icon {
        width: 32px;
        height: 32px;
        margin-right: 12px;
      }
    }

    .head-right {
      font-size: 14px;
      font-weight: 400;
      color: rgba(255, 255, 255, 1);
      display: flex;
      align-items: baseline;
      cursor: pointer;
    }
  }

  .head-timer {
    height: 70px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #FFFFFF;

    .timer-name {
      font-size: 14px;
      font-weight: 400;
      color: rgba(255, 255, 255, 1);
    }

    ::v-deep .el-range-editor.el-input__inner {
      flex: 1;
      height: 32px;
      border: 2px solid rgba(255, 255, 255, 0.12);
      background: #1B1645;
      color: rgba(255, 255, 255, 1);
    }

    ::v-deep .el-range__icon {
      line-height: 22px;
    }

    ::v-deep .el-range__close-icon,
    ::v-deep.el-range-separator {
      background: #1B1645;
      color: rgba(255, 255, 255, 1);
      line-height: 22px;
    }

    ::v-deep .el-range-input {
      background: #1B1645;
      color: rgba(255, 255, 255, 1);
    }

    ::v-deep .el-button--primary {
      width: 76px;
      height: 32px;
      margin-left: 16px;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #466BE3;
      border-color: #466BE3;
    }

    ::v-deep .el-button--info {
      width: 76px;
      height: 32px;
      margin-left: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #56517A;
      border-color: #56517A;
    }
  }

  .list-nav {
    flex: 1;
    width: 100%;
    height: 100%;
    position: relative;

    ::v-deep .el-table,
    ::v-deep tr,
    ::v-deep th {
      background-color: #2C2559;
      color: #fff
    }

    ::v-deep .el-table--enable-row-hover .el-table__body tr:hover {
      background: transparent;
    }

    ::v-deep .el-table tbody tr:hover>td {
      background-color: transparent !important;
    }

    ::v-deep .el-table,
    ::v-deep .el-table__header-wrapper th,
    ::v-deep .el-table__body-wrapper td {
      border-color: transparent !important;
    }

    ::v-deep .el-table,
    ::v-deep .el-table__header-wrapper th,
    ::v-deep .el-table__body-wrapper td {
      border-width: 0 !important;
    }

    ::v-deep .el-table::before {
      height: 0;
    }

    /* 表格底部加载状态样式 */
    .table-footer {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #2C2559;
      border-top: 1px solid #342F66;

      .loading-row,
      .no-more-row {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        height: 100%;
        width: 100%;
      }

      .loading-row {
        color: #466BE3;

        i {
          margin-right: 8px;
          font-size: 16px;
        }
      }

      .no-more-row {
        color: #999;
      }
    }

    /* 优化name字段样式 */
    .table-name {
      width: 75px;
      height: 100%;
      overflow: hidden;
      position: relative;
      display: flex;
      align-items: center;

      .name-text {
        white-space: nowrap;
        padding: 0 2px;
        display: inline-block;
        text-overflow: ellipsis;

        /* 滚动状态 */
        &.auto-scroll {
          animation: continuousScroll 3s linear infinite;
          padding-left: 100%; /* 初始位置在右侧 */
        }
      }
    }
  }
}

/* 持续滚动动画 */
@keyframes continuousScroll {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(-100%);
  }
}

/* 针对表格行的样式调整 */
::v-deep .el-table .cell {
  padding: 0 8px;
  line-height: 23px;
}

::v-deep .el-table td {
  padding: 4px 0;
}
</style>
